<?php
/**
 * @Description: 教研活动
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Teaching;

use App\Http\Controllers\Excel\ExcelExport;
use App\Models\ActivityInfo;
use App\Models\DecSubject;
use App\Models\File;
use App\Models\Files;
use App\Models\FormInstance;
use App\Models\Participant;
use App\Models\System\Tasks;
use App\Models\System\Term;
use App\Models\System\User;
use App\Models\Teaching\TeachingComment;
use App\Models\Teaching\HomeworkInfo;
use App\Models\Teaching\HomeworkScore;
use App\Models\Teaching\TeachingActivity;
use App\Models\Teaching\TeachingHomework;
use App\Models\Teaching\TeachingSign;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Intervention\Image\Facades\Image;

/**
 * 教研活动 (服务)
 */
class ActivityService
{
    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;
    /** @var \App\Repositories\System\ParticipantRepository $participantRepository */
    private $participantRepository;
    /** @var \App\Repositories\Teaching\TeachingActivityRepository $teachingActivityRepository */
    private $teachingActivityRepository;
    /** @var \App\Repositories\Teaching\TeachingHomeworkRepository $teachingHomeworkRepository */
    private $teachingHomeworkRepository;
    /** @var \App\Repositories\System\DictionaryItemRepository $dictionaryItemRepository */
    private $dictionaryItemRepository;

    private $formKey = 'TEACHERTRAINING_ACTIVITY_TABLE';

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
        $this->participantRepository = app('participantRepository');
        $this->teachingActivityRepository = app('teachingActivityRepository');
        $this->teachingHomeworkRepository = app('teachingHomeworkRepository');
        $this->dictionaryItemRepository = app('dictionaryItemRepository');
    }


    /**
     * @Description: 教研活动列表信息数据
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function getList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;

        $name = '';
        $termId = 0;
        $status = 0;
        $level = '';
        $rangeDate = [];
        $jsonSearch = [];
        $viewAll = false;
        $activityType = '';
        $creatorName = ''; //创建人

        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['activity_type']) && !empty($request['search']['activity_type'])){
            $activityType = $request['search']['activity_type'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $level = $request['search']['level'];
        }
        if (isset($request['search']['range_date'] )&& !empty($request['search']['range_date'])){
            $rangeDate = explode(' - ', $request['search']['range_date']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        if (isset($request['search']['status'] )&& !empty($request['search']['status'])){
            $status = $request['search']['status'];
        }

        $now = now();
        $user = Auth::user();
        //非审核权限只能看到自己提交的数据
        if(is_check(249)){
            $viewAll = true;
        }

        $result = ActivityInfo::select('activity_info.id', 'activity_info.data_version_id', 'activity_info.data_version_name', 'activity_info.name', 'activity_info.level', 'activity_info.begin_date', 'activity_info.end_date', 'activity_info.creator_id', 'activity_info.course', 'activity_info.created_at', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
            ->with(['term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status', 'teachingActivity'])
            ->where('activity_info.activity_category', $this->formKey)
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($activityType, function($q) use($activityType) {
                $q->whereHas('teachingActivity', function ($query) use($activityType) {
                    $query->where('activity_type', $activityType);
                });
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    if($k == 'course') {
                        $q->where('course', 'like', '%'.$id.',%');
                    } else {
                        $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                    }
                }
            })
            ->when($level, function($q) use($level) {
                // $q->whereRaw(" activity_info.`level`->'$[0].selectValue' = $level")
                // $q->where('activity_info.level', 'like', '%' . $level . '%')->orWhere(function ($qq) use($level) {
                //     $qq->whereHas('teachingActivity', function ($query) use($level) {
                //         $query->where('activity_level', 'like', '%'.$level.'%');
                //     });
                // });
                $q->whereHas('teachingActivity', function ($query) use($level) {
                    $query->where('activity_level', 'like', '%'.$level.',%');
                });
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){
                $q->whereRaw("((`activity_info`.`creator_id` = ".$request['user_id'].") or (`p`.`user_id` = ".$request['user_id'] .")) ");//and `activity_info`.`end_date` < '".date('Y-m-d')."'
                //and `activity_info`.`end_date` > '".date('Y-m-d')
            })
            ->when(!isset($request['user_id']), function($q) use($name) {
                $q->manageable();
            })
            /**
            ->when(!$viewAll && !$user->is_checker, function($q) use($user){
                $q->whereHas('participants', function($query) use($user){
                    $query->where('user_id', $user->id);
                });
             })**/

            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when($status > 0, function($q) use($status, $now) {
                if($status == 1) {
                    $q->where('begin_date', '>', $now);
                } elseif($status == 2) {
                    $q->where('begin_date', '<', $now)->where('end_date', '>', $now);
                } elseif($status == 3) {
                    $q->where('end_date', '<', $now);
                }
            })
            ->where('activity_info.deleted', 0)
            ->groupBy('activity_info.id')
            ->orderBy('activity_info.id', 'desc')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();
        foreach ($result['data'] as &$item){
            if($user->id == $item['creator_id']) {
                $item['is_createor'] = 1;
            }else{
                $item['is_createor'] = 0;
            }
            $item['is_part'] = 0;
            if(!empty($item['participant'])) {
                $participant = array_column($item['participant'], 'user_id');
                if (in_array($user->id, $participant) && $item['is_createor'] != 1) {
                    $item['is_part'] = 1;
                }
            }
        }
        return $result;
    }

    /**
     * @Description: 教研活动添加
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function add($request)
    {
        if(empty($request['activity_category'])) {
            throw new \Exception('参数缺失！');
        }

        $now = now();
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        $status = $request['status'] == 1 ? 'REVIEW' : 'FILL_IN';
        unset($request['file']);
        unset($request['status']);
        // dd(1, $request);
        try{
            DB::beginTransaction();
            // //请求数据处理
            $activityData = $this->activityRepository->dealRequestData($request);

            // //添加状态及审核信息
            $formInstance = FormInstance::create([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'form_key'=> $request['activity_category'],
                'type' => 'MainForm',
                'owner_id' => $user->id,
                'status' => $status,
                'creator_id' => $user->id,
            ]);

            //添加数据
            $activityData['creator_id'] = $user->id;
            $activityData['data_version_name'] = $term->title;
            $activityData['form_instance_id'] = $formInstance->id;
            $result = ActivityInfo::create($activityData);

            //添加教研活动表相关信息
            $teachingActivityData = $this->teachingActivityRepository->dealRequestData($request);
            $teachingActivityData['created_at'] = $now;
            $teachingActivityData['updated_at'] = $now;
            TeachingActivity::updateOrCreate(['activity_id' => $result->id], $teachingActivityData);

            //添加主讲教师
            if(isset($request['compere']) && !empty($request['compere'])) {
                $comperes = explode(',', $request['compere']);
                $this->participantRepository->addParticipant($result->id, $comperes, 'COMPERE');

                //添加待办事项
                if($status == 'REVIEW'){
                    foreach($comperes as $pere) {
                        $task = Tasks::where('form_id', $result->id)
                            ->where('form_key', $this->formKey)
                            ->where('c_user_id', $pere)
                            ->where('status', 1)
                            ->first();

                        if(!$task) {
                            Tasks::create([
                                'name' => '【' . $term->title . '】教学研究-教研活动布置作业',
                                'data_version_id' => $term->id,
                                'form_id' => $result->id,
                                'form_key' => $this->formKey,
                                'start_date' => date('Y-m-d H:i:s'),
                                'end_date' => $request['end_date'],
                                'type' => 2,
                                'c_user_id' => $pere,
                                'creator_id' => $user->id,
                                'creator_name' => $user->nickname,
                                'param' => '?id=' . $result->id,
                                'url' => '/teaching/activity/homework',
                                'menu_id'=> 252
                            ]);
                        }
                    }
                }
            }

            //添加参加教师
            if(isset($request['participant']) && !empty($request['participant'])) {
                $participants = explode(',', $request['participant']);
                $this->participantRepository->addParticipant($result->id, $participants);
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 添加编辑教研活动作业表相关信息
     * @Author: kzj
     * @datetime: 2023-03-16
     */
    public function addHomework($request)
    {
        if(empty($request['activity_id'])) {
            throw new \Exception('参数缺失！');
        }

        unset($request['form_index']);

        if(!isset($request['live_id'])) {
            $request['live_id'] = 0;
        }

        if(isset($request['link_id']) && !empty($request['link_id'])) {
            $request['link_id'] = implode(',', $request['link_id']);
        }

        $user = Auth::user();
        $activity = ActivityInfo::whereId($request['activity_id'])->first();
        $participants = $activity->participant;

        try{
            DB::beginTransaction();

            if($request['homework_id']) {
                $hwid = $request['homework_id'];
                unset($request['homework_id']);
                TeachingHomework::whereId($hwid)->update($request);
                $result = TeachingHomework::whereId($hwid)->with('live:id,name')->first();
            } else {
                unset($request['homework_id']);

                $createData = TeachingHomework::create($request);

                $result = TeachingHomework::whereId($createData->id)->with('live:id,name')->first();
            }

            $activity = ActivityInfo::whereId($request['activity_id'])->first();

            // 主讲老师待办状态更新
            Tasks::where('form_id', $activity->id)->where('form_key', $this->formKey)->where('c_user_id', $user->id)->update(['status' => 2]);

            // 参与老师添加待办
            if($participants) {
                foreach($participants as $pant) {
                    $task = Tasks::where('form_id', $activity->id)
                        ->where('form_key', $this->formKey)
                        ->where('c_user_id', $pant->user_id)
                        ->where('status', 1)
                        ->first();

                    if(!$task) {
                        Tasks::create([
                            'name' => '【' . $activity->data_version_name . '】教学研究-教研活动参与',
                            'data_version_id' => $activity->data_version_id,
                            'form_id' => $activity->id,
                            'form_key' => $this->formKey,
                            'start_date' => $activity->begin_date,
                            'end_date' => $activity->end_date,
                            'type' => 2,
                            'c_user_id' => $pant->user_id,
                            'creator_id' => $user->id,
                            'creator_name' => $user->nickname,
                            'param' => '?id=' . $activity->id,
                            'url' => '/teaching/activity/join',
                            'menu_id'=> 251
                        ]);
                    }
                }
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }


    /**
     * @Description: 教研活动单条数据
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function one($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $result = ActivityInfo::where('id', $request['id'])
            ->with([
                'creator', 'participants', 'instance:id,status,comment', 'stages', 'comments',
                'homework' => function($q) {
                    $q->with('live:id,name');
                },
                'teachingActivity' => function($q) {
                    $q->with('live:id,name');
                }
            ])
            ->withCount('comments')
            ->first();

        return $result;
    }

    /**
     * @Description: 教研活动编辑
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function edit($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $status = 'REVIEW';
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        unset($request['file']);

        try{
            DB::beginTransaction();
            //请求数据处理
            $activityData = $this->activityRepository->dealRequestData($request);

            $activityData['updater_id'] = $user->id;
            $activityData['data_version_name'] = $term->title;

            $result = ActivityInfo::whereId($request['id'])->update($activityData);
            $activityInfo = ActivityInfo::whereId($request['id'])->with('participants', 'compere')->first();

            //编辑状态及审核信息
            FormInstance::whereId($activityInfo->form_instance_id)->update([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'status' => $status,
                'updater_id' => $user->id
            ]);

            //编辑教研活动表相关信息
            $teachingActivityData = $this->teachingActivityRepository->dealRequestData($request);
            TeachingActivity::updateOrCreate(['activity_id' => $activityInfo->id], $teachingActivityData);

            //编辑主讲教师
            if(isset($request['compere']) && !empty($request['compere'])) {
                $comperes = explode(',', $request['compere']);
                $pus = $activityInfo->participants_users;
                if(empty($pus->pere)) {
                    $this->participantRepository->addParticipant($request['id'], $comperes, 'COMPERE');
                } else {
                    $isSame = array_diff_assoc($comperes, $pus->pere, 'COMPERE');
                    if(!empty($isSame)) {
                        $this->participantRepository->addParticipant($request['id'], $comperes, 'COMPERE');
                    }
                }
            }
            //编辑参加教师
            if(isset($request['participant']) && !empty($request['participant'])) {
                $participants = explode(',', $request['participant']);
                $pus = $activityInfo->participants_users;
                if(empty($pus->pant)) {
                    $this->participantRepository->addParticipant($request['id'], $participants);
                } else {
                    $isSame = array_diff_assoc($participants, $activityInfo->pant);
                    if(!empty($isSame)) {
                        $this->participantRepository->addParticipant($request['id'], $participants);
                    }
                }
            }

            //删除涉及作业修改的直播资源及文件
            if(isset($request['live_id'])) {
                TeachingHomework::where('activity_id', $request['id'])->where('live_id', '>', 0)->where('live_id', '!=', $request['live_id'])->delete();
            }

            $deleteFileIds = json_decode($request['delete_file_ids']);
            $homeworkData = TeachingHomework::where('activity_id', $request['id'])->where('link_id', '!=', '')->get();
            if(!empty($deleteFileIds) && $homeworkData->count()) {
                foreach($homeworkData as $item) {
                    $isHad = collect($item->link_set)->whereIn('id', $deleteFileIds);
                    if($isHad->count()) {
                        TeachingHomework::whereId($item->id)->delete();
                    }
                }
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }


    /**
     * @Description: 教研活动删除
     * @Author: kzj
     * @datetime: 2023-03-15
     */
    public function del($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        dd($request);

        // $result = Live::whereId($request['id'])->update(['deleted' => 1]);

        // return $result;
    }

    /**
     * @Description: 教研活动文件下载
     * @Author: kzj
     * @datetime: 2023-03-28
     */
    public function download($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $activity = ActivityInfo::select('id', 'name')
            ->whereId($request['id'])
            ->with('participant:id,activity_info_id,user_id', 'homeworkInfo:id,activity_id,user_id,resource')
            ->first();

        $participants = $activity->participant;
        $homeworkInfo = $activity->homeworkInfo;

        if(!$participants->count()) {
            throw new \Exception('活动没有选择参与人！');
        }
        if(!$homeworkInfo->count()) {
            throw new \Exception('没有上传的作业文件!');
        }

        $zipPath = public_path().'/download/zip'; //zip路径
        $fileName = '教研活动_' . $activity->name . '_' . date('Ymd').'.zip';
        $zipFileName = $zipPath.'/'.$fileName; //zip名称加路径

        $zip = new \ZipArchive();
        if($zip->open($zipFileName, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true){
            foreach($participants as $pant) {
                $userHomework = $homeworkInfo->where('user_id', $pant->user_id);
                if(!$userHomework->count()) {
                    continue;
                }

                $resources = $userHomework->pluck('resource_set')->flatten(1);//处理成一维数组
                if($resources->count()) {
                    if($zip->addEmptyDir($pant->user->nickname)) {
                        foreach($resources as $res) {
                            $filePath = public_path() . $res['file_info']['file_dir'] . $res['file_info']['file_path'];//文件真实存在路径
                            $zip->addFile($filePath, $pant->user->nickname . '/' . $res['file_info']['file_name']);//压缩文件存储路径
                        }
                    } else {
                        Log::info('Could not create the directory: ' . $pant->user->nickname);
                    }
                }
            }
        }
        @$zip->close();

        if(file_exists($zipFileName)){
            return ['file_name' => $fileName];
        }else{
            throw new \Exception('没有上传作业文件');
        }
    }

    /**
     * @Description: 教研活动删除作业
     * @Author: kzj
     * @datetime: 2023-03-16
     */
    public function delHomework($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $result = TeachingHomework::whereId($request['id'])->delete();

        return $result;
    }

    /**
     * @Description: 作业数据
     * @Author: kzj
     * @datetime: 2023-03-23
     */
    public function getHomeworkInfo($request)
    {
        if(!$request['activity_id']) {
            throw new \Exception('ID参数缺失！');
        }

        $user = Auth::user();
        $userId = $user->id;
        if($request['user_id'] > 0) {
            $userId = $request['user_id'];
        }

        $result = TeachingHomework::where('activity_id', $request['activity_id'])
            ->with(['live', 'scaleMore',
                'more' => function($q) use($userId) {
                    //处理查看当前所属作业情况
                    $q->where('user_id', $userId);
                },
                'score' => function($q) use($userId) {
                    //处理查看当前所属作业情况
                    $q->where('user_id', $userId);
                }
            ])
            ->get();

        return $result;
    }

    /**
     * @Description: 作业提交
     * @Author: qiankun
     * @datetime: 2023-03-23
     */
    public function saveHomework($request)
    {
        if(!$request['homework_id']) {
            throw new \Exception('参数缺失！');
        }

        $now = now();
        $user = Auth::user();
        $scoreInfo = [];
        if(isset($request['score_info']) && !empty($request['score_info'])) {
            $scoreInfo = $request['score_info'];
        }

        try{
            DB::beginTransaction();
            //保存作业量表评分
            if(!empty($scoreInfo)) {
                foreach($scoreInfo as $info) {
                    $item = (array) json_decode($info);
                    if(empty($item)) {
                        throw new \Exception('评分没有完成，不能提交！');
                    } else {
                        HomeworkScore::updateOrCreate([
                            'homework_id' => $request['homework_id'],
                            'user_id' => $user->id,
                            'scale_id' => $request['scale_id'],
                            'detail_id' => $item['detail_id'],
                        ],[
                            'score' => $item['score'],
                            'score_date' => $now,
                        ]);
                    }
                }
            }

            //保存作业基本信息
            $homeworkInfo = [];
            if(isset($request['files'])) {
                $uploadedFile = $this->activityRepository->dealUploadFile($request['files']);
                $homeworkInfo['resource'] = json_encode($uploadedFile);
            }
            if(isset($request['describe'])) {
                if(!$request['describe']) {
                    throw new \Exception('总结性描述不能为空！');
                }
                $homeworkInfo['describe'] = $request['describe'];
            }
            if(!empty($homeworkInfo)) {
                // 计算总分保存
                $score = 0;
                if(!empty($scoreInfo)) {
                    $score = HomeworkScore::where('homework_id',  $request['homework_id'])->where('user_id', $user->id)->sum('score');
                }
                $homeworkInfo['score'] = $score;
                $homeworkInfo['activity_id'] = $request['activity_id'];

                $homeworkResponse = HomeworkInfo::updateOrCreate(['homework_id' => $request['homework_id'], 'user_id' => $user->id], $homeworkInfo);
            }
            //dd($homeworkResponse->user_id,$request['activity_id']);
            //$participant = Participant::where('activity_info_id',$request['activity_id'])->where('user_id',$homeworkResponse->user_id)->first();
            if(isset($request['files'])) {
                $participantResponse = ActivityInfo::find($request['activity_id']);
                $participantResponse->files_id = array_column($uploadedFile, 'files_id');
            }
            // 参与老师待办状态更新
            Tasks::where('form_id', $request['activity_id'])->where('form_key', $this->formKey)->where('c_user_id', $user->id)->update(['status' => 2]);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    /**
     * @Description: 添加评论
     * @Author: kzj
     * @datetime: 2023-03-23
     */
    public function addComment($request)
    {
        if(!$request['activity_id']) {
            throw new \Exception('参数缺失！');
        }
        if(!$request['comment']) {
            throw new \Exception('评论不能为空！');
        }

        $user = Auth::user();
        $request['user_id'] = $user->id;
        $request['user_name'] = $user->nickname;

        try{
            DB::beginTransaction();
            TeachingComment::create($request);

            $result = TeachingComment::where('activity_id', $request['activity_id'])->orderBy('id', 'desc')->get();

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 生成二维码
     * @Author: kzj
     * @datetime: 2023-03-24
     */
    public function getQRCode($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $id = (int) $request['id'];

        $path = public_path();
        $filname = '/uploads/qrcode/qrcode_xyhd_'.$id.'.png';
        $filePath = $path.$filname;

        if(file_exists($filePath)){
            unlink($filePath);
        }

        $url = route('qrcode.index').'?id='.$id;
        //生成二维码
        \QRcode::png($url,$filePath,'L',8,2);

        return [
            'qrcode' => $filname ,
            'url'=> $url
        ];
    }

    /**
     * @Description: 签到
     * @Author: kzj
     * @datetime: 2023-03-27
     */
    public function addSign($request)
    {
        if(!$request['activity_id']) {
            throw new \Exception('参数缺失！');
        }

        $user = User::where('username', $request['user_id'])->first();
        if(!$user) {
            throw new \Exception('账号填写错误，无此账号用户！');
        }
        $isPant = Participant::where('activity_info_id', $request['activity_id'])->where('user_id', $user->id)->first();
        if(!$isPant) {
            throw new \Exception('用户没有参与此教研活动，请确认！');
        }

        $now = now();
        $result = TeachingSign::updateOrCreate([
            'user_id' => $user->id,
            'activity_id' => $request['activity_id']
        ], [
            'user_name' => $user->nickname,
            'sign_status' => 1,
            'sign_time' => $now
        ]);

        return $result;
    }

    /**
     * @Description: 活动参与进度数据
     * @Author: kzj
     * @datetime: 2023-03-27
     */
    public function getJoinList($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;

        $activity = ActivityInfo::select(['id', 'data_version_id'])
            ->where('id', $request['id'])
            ->with('participant')
            ->withCount('participant', 'homework')
            ->first();

        $name = "";
        $classId = 0;
        $subjectId = 0;
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $subjectId = $request['search']['course'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $classId = $request['search']['class_item'];
        }

        // $lists = Participant::where('activity_info_id', $request['id'])
        $rows = Participant::where('activity_info_id', $request['id'])
            ->where('participant_type', 'PARTICIPANT')
            ->with([
                'user:id,nickname',
                'sign' => function($q) use($activity) {
                    $q->where('activity_id', $activity->id);
                },
                'homework' => function($q) use($activity) {
                    $q->where('activity_id', $activity->id);
                },
                'teachingSubject' => function($q) use($activity) {
                    $q->where('data_version_id', $activity->data_version_id);
                }
            ])
            ->when($name, function($q) use($name) {
                $q->whereHas('user', function ($query) use($name) {
                    $query->where('nickname', 'like', '%' . $name . '%');
                });
            })
            ->when($classId > 0, function($q) use($classId, $activity) {
                $q->whereHas('teachingSubject', function ($query) use($classId, $activity) {
                    $query->where('data_version_id', $activity->data_version_id)->whereRaw(" JSON_EXTRACT(`class_item`,'$[0].optionId') = $classId");
                });
            })
            ->when($subjectId > 0, function($q) use($subjectId, $activity) {
                $q->whereHas('teachingSubject', function ($query) use($subjectId, $activity) {
                    $query->where('data_version_id', $activity->data_version_id)->whereRaw(" JSON_EXTRACT(`subject_dic_items`,'$[0].optionId') = $subjectId");
                });
            })
            ->orderBy('id', 'desc');//->get()->toArray();
            // ->paginate($limit, '*', 'page', $page);

        $res = $rows->get();
        $lists = $rows->paginate($limit, '*', 'page', $page);
        // dd($lists, $res);
        $pantTotal = $activity->participant_count;
        $homeworkTotal = $activity->homework_count;
        // dd($homeworkTotal, $activity->toArray());

        // dd($lists->items());
        $items = [];
        $pendingCount = 0;
        $doneCount = 0;
        foreach($lists->items() as $l) {
            $item['activity_id'] = $activity->id;
            $item['user_id'] = $l->user ? $l->user->id : 0;
            $item['name'] = $l->user ? $l->user->nickname : '';
            $item['subject_info'] = $l->teaching_info ? $l->teaching_info['subjects'] : '-';
            $item['class_info'] = $l->teaching_info ? $l->teaching_info['classes'] : '-';
            $item['sign_status'] = $l->sign ? true : false;
            $item['is_push'] = $l->is_push;
            $homeworkCount = $l->homework->count();
            $homeworkFirst = $l->homework->first();
            $item['homework'] = $homeworkCount .' / '. $homeworkTotal;
            $item['sub_date'] = $homeworkCount > 0 ? Carbon::parse($homeworkFirst->created_at)->toDateTimeString() : '';
            $items[] = $item;
        }

        foreach($res as $k => $r) {
            $homeworkCount = $r->homework->count();
            if($homeworkCount > 0) {
                if($homeworkCount == $homeworkTotal) {
                    $doneCount++;
                } else {
                    $pendingCount++;
                }
            } else {
                $pendingCount++;
            }
        }

        $result = [
            'list' => [
                'data' => $items,
                'total' => $lists->total(),
                'limit' => $lists->perPage()
            ],
            'statistic' => [
                'total' => $pantTotal,
                'done' => $doneCount,
                'pending' => $pendingCount
            ]
        ];

        return $result;
    }

    /**
     * @Description: 活动参与进度数据导出
     * @Author: kzj
     * @datetime: 2023-03-27
     */
    public function export($request)
    {
        if(!$request['id']) {
            throw new \Exception('参数缺失！');
        }

        $activity = ActivityInfo::select(['id', 'data_version_id'])
            ->where('id', $request['id'])
            ->with('participant')
            ->withCount('participant', 'homework')
            ->first();

        $name = "";
        $classId = 0;
        $subjectId = 0;
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $subjectId = $request['search']['course'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $classId = $request['search']['class_item'];
        }

        $lists = Participant::where('activity_info_id', $request['id'])
            ->where('participant_type', 'PARTICIPANT')
            ->with([
                'user:id,nickname',
                'sign' => function($q) use($activity) {
                    $q->where('activity_id', $activity->id);
                },
                'homework' => function($q) use($activity) {
                    $q->where('activity_id', $activity->id);
                },
                'teachingSubject' => function($q) use($activity) {
                    $q->where('data_version_id', $activity->data_version_id);
                }
            ])
            ->when($name, function($q) use($name) {
                $q->whereHas('user', function ($query) use($name) {
                    $query->where('nickname', 'like', '%' . $name . '%');
                });
            })
            ->when($classId > 0, function($q) use($classId, $activity) {
                $q->whereHas('teachingSubject', function ($query) use($classId, $activity) {
                    $query->where('data_version_id', $activity->data_version_id)->whereRaw(" JSON_EXTRACT(`class_item`,'$[0].optionId') = $classId");
                });
            })
            ->when($subjectId > 0, function($q) use($subjectId, $activity) {
                $q->whereHas('teachingSubject', function ($query) use($subjectId, $activity) {
                    $query->where('data_version_id', $activity->data_version_id)->whereRaw(" JSON_EXTRACT(`subject_dic_items`,'$[0].optionId') = $subjectId");
                });
            })
            ->orderBy('id', 'desc')
            ->get();

        $homeworkTotal = $activity->homework_count;

        $i = 1;
        $exportData = [];
        foreach($lists as $l) {
            $item['key'] = $i;
            $item['name'] = $l->user ? $l->user->nickname : '';
            $item['subject_info'] = $l->teaching_info ? $l->teaching_info['subjects'] : '-';
            $item['class_info'] = $l->teaching_info ? $l->teaching_info['classes'] : '-';
            $item['sign_status'] = $l->sign ? '已签到' : '未签到';

            $homeworkCount = $l->homework->count();
            $homeworkFirst = $l->homework->first();
            $item['homework'] = $homeworkCount .' / '. $homeworkTotal;
            $item['sub_date'] = $homeworkCount > 0 ? Carbon::parse($homeworkFirst->created_at)->toDateTimeString() : '';
            $exportData[] = $item;

            $i++;
        }

        $title = ['序号','教师姓名','任教学科','任教班级','签到状态','作业完成进度','提交时间'];
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    /**
     * @Description: 教师个人作业文件下载
     * @Author: kzj
     * @datetime: 2023-03-28
     */
    public function downloadHomework($request)
    {
        if(!$request['activity_id'] || !$request['user_id']) {
            throw new \Exception('参数缺失！');
        }

        $user = User::select('id', 'nickname')->whereId($request['user_id'])->first();
        $result = HomeworkInfo::where('activity_id', $request['activity_id'])->where('user_id', $request['user_id'])->get();
        if(!$result->count()){
            throw new \Exception('没有上传作业文件');
        }

        $zip_path = public_path().'/download/zip'; //zip路径
        $file_name = $user->nickname . '_' . date('YmdHis').'.zip';
        $zip_filename = $zip_path.'/'.$file_name; //zip名称加路径
        $zip = new \ZipArchive();
        // dd($zip_filename);
        if($zip->open($zip_filename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true){
            foreach($result as $item){
                if($item->resource_set) {
                    foreach($item->resource_set as $res) {
                        $filePath = public_path() . $res['file_info']['file_dir'] . $res['file_info']['file_path'];

                        $zip->addFile($filePath, $res['file_info']['file_name']);
                    }
                } else {
                    continue;
                }
            }
        }
        @$zip->close();

        if(file_exists($zip_filename)){
            return [
                'file_name' => $file_name,
            ];
        }else{
            throw new \Exception('没有上传作业文件');
        }
    }


    /**
     * @Description: 列表数据导出
     * @Author: kzj
     * @datetime: 2023-11-27
     */
    public function exportTeaActivity($request)
    {
        $name = '';
        $termId = 0;
        $status = 0;
        $rangeDate = [];
        $jsonSearch = [];
        $viewAll = false;
        $activityType = '';
        $creatorName = ''; //创建人

        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['activity_type']) && !empty($request['search']['activity_type'])){
            $activityType = $request['search']['activity_type'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['range_date'] )&& !empty($request['search']['range_date'])){
            $rangeDate = explode(' - ', $request['search']['range_date']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        if (isset($request['search']['status'] )&& !empty($request['search']['status'])){
            $status = $request['search']['status'];
        }

        $now = now();
        $user = Auth::user();
        //非审核权限只能看到自己提交的数据
        if(is_check(249)){
            $viewAll = true;
        }

        $output = ActivityInfo::select('activity_info.id', 'activity_info.data_version_id', 'activity_info.data_version_name', 'activity_info.name', 'activity_info.level', 'activity_info.begin_date', 'activity_info.end_date', 'activity_info.creator_id', 'activity_info.course', 'activity_info.created_at', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->with(['term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status', 'teachingActivity'])
            ->where('activity_info.activity_category', $this->formKey)
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($activityType, function($q) use($activityType) {
                $q->whereHas('teachingActivity', function ($query) use($activityType) {
                    $query->where('activity_type', $activityType);
                });
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){
                $q->where('activity_info.creator_id', $request['user_id']);
            })
            ->when(!$viewAll && !$user->is_checker, function($q) use($user){
                $q->whereHas('participants', function($query) use($user){
                    $query->where('user_id', $user->id);
                });
             })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when($status > 0, function($q) use($status, $now) {
                if($status == 1) {
                    $q->where('begin_date', '>', $now);
                } elseif($status == 2) {
                    $q->where('begin_date', '<', $now)->where('end_date', '>', $now);
                } elseif($status == 3) {
                    $q->where('end_date', '<', $now);
                }
            })
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();

        // dd($output->toArray());

        $title = ['学年学期','教研名称','活动类别','级别','学科','开始日期','结束日期','创建人','状态'];
        $exportData = [];
        foreach($output as $k => $v){
            $activityType = '';
            if($v->teachingActivity) {
                $activityType = $v->teachingActivity['activity_type_name'] ?? '-';
            } else {
                $activityType = '-';
            }

            $level = $v->level && !empty($v->level_array) ? $v->level_array[0]['selectValue'] : '校级';
            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $v->name,
                'type' => $activityType,
                'level' => $level,
                'course' => !empty($v->course_set) ? $v['course_set'][0]['selectValue'] : '',
                'begin_date' => $v->begin_date,
                'end_date' => $v->end_date,
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'status' => $v->activity_date_status
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    /*
     * @Description: 开发科目复用
     * @Author:  Kzj
     * @Date: 2024-01-29 15:14:54
     */
    public function copySubject($request)
    {
        if (!$request['id']) {
            throw new \Exception('参数错误！');
        }

        $user = Auth::user();

        DB::beginTransaction();
        try
        {
            $subject = ActivityInfo::find($request['id'])->replicate();

            //添加状态及审核信息
            $formInstance = FormInstance::create([
                'data_version_id' => $subject->data_version_id,
                'data_version_name' => $subject->data_version_name,
                'form_key'=> 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE',
                'type' => 'MainForm',
                'owner_id' => $user->id,
                'status' => 'FILL_IN',
                'creator_id' => $user->id,
            ]);

            //添加数据
            $subject->form_instance_id = $formInstance->id;
            $subject->creator_id = $user->id;
            $subject->copy_id = $request['id'];
            $subject->save();

            // $participantIds = Participant::where('activity_info_id', $request['id'])->get()->pluck('user_id')->toArray();
            // if(!empty($participantIds)) {
            //     $this->participantRepository->addParticipant($subject->id, $participantIds);
            // }

            DB::commit();
        }
        catch(\Exception $e)
        {
            DB::rollBack();
            Log::error($e->getMessage());
            throw new \Exception('数据保存错误！');
        }

        return true;
    }

    /*
     * @Description: 生成证明单
     * @Author:  Kzj
     * @Date: 2024-01-30 15:23:16
     */
    public function generateCertificate($request)
    {
        // if($request['zm_style'] == 1 && !$request['zm_gkk_category']) {
        //     throw new \Exception('公开课类别不能为空！');
        // }
        unset($request['file']);
        unset($request['files']);

        $now = now();
        $savePath = public_path('back-end/uploadfiles/image/' . $now->format('Ym'));
        if(!is_readable($savePath)) {
            mkdir($savePath, 0777, true);
        }

        $dicIds = [
            $request['level'],
            $request['course'],
            $request['grade']
        ];
        // dd($request);
        $dicArr = $this->dictionaryItemRepository->getDictionaryItem($dicIds);
        // dd($dicArr->toArray());

        try{
            DB::beginTransaction();

            $result = $this->generateZmd($request, $dicArr, $savePath);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    // 生成证明单
    public function generateZmd($request, $dicArr, $savePath)
    {
        $user = Auth::user();
        $imagePath = public_path('app/images/zmdjz2.jpg');
        // $fontPath = public_path('app/fonts/st.ttf');
        // $fontPath = './app/fonts/st.ttf';
        $img = Image::make($imagePath)->resize(1200, 1700);
        $categoryDistance = in_array($request['activity_category'], ['EW_CLASS_MEETING_TABLE', 'TEARRESEARCH_OPEN_TABLE']) ? 500 : 740;

        $creatorName = $this->to_unicode($user->nickname);
        $themeName = $this->to_unicode($request['name']);
        $workPlace = $this->to_unicode('华东理工大学附属小学');
        $zmrzw = $this->to_unicode($request['witness_position']);

        $courseDic = $dicArr->where('optionId', $request['course'])->first();
        $decSubject = DecSubject::query()->select('id as optionId','name as selectValue','name as selectKey')
            ->where('id', $request['course'])->first();
        $courseName = $decSubject ? $decSubject->selectValue : '';
        $gradeDic = $dicArr->where('optionId', $request['grade'])->first();
        $gradeName = $gradeDic ? $this->to_unicode($gradeDic->selectValue) : '';
        $levelDic = $dicArr->where('optionId', $request['level'])->first();
        $levelName = $courseDic ? $levelDic->selectValue : '';
        $date = $this->to_unicode($request['begin_date']);
        $signDate = date('Y年m月d日', strtotime($request['begin_date']));
        $place = $this->to_unicode($request['place']);
        $target = $this->to_unicode($request['target']);
        $remark = $request['zmd_remark'] ? $this->to_unicode($request['zmd_remark']) : '';

        // $zmStyle = $request['zm_style'] == 1 ? '公开课' : '研究课';
        // $zmStyleName = $this->to_unicode($zmStyle);
        // $zmgkkCategory = '';
        // switch ($request['zm_gkk_category']) {
        //     case 1:
        //         $zmgkkCategory = $levelName . '讲座';
        //         break;
        //     case 2:
        //         $zmgkkCategory = $levelName . '交流';
        //         break;
        // }
        // $zmgkkCategoryName = $zmgkkCategory ? $this->to_unicode($zmgkkCategory) : '';
        $zmStyleName = $this->to_unicode('校级公开课');
        $zmgkkCategoryName = $this->to_unicode('校级讲座');


        $zmrs = User::whereIn('id', $request['zmr_ids'])->get();
        $fzrs = User::whereIn('id', $request['fzr_ids'])->get();
        $zmrsInfo = $zmrs->count() > 0 ? $this->to_unicode($zmrs->pluck('nickname')->implode(' ')) : '';
        $fzrsInfo = $zmrs->count() > 0 ? $this->to_unicode($fzrs->pluck('nickname')->implode(' ')) : '';

        /**
        $fontPath = public_path('app/fonts/st.ttf');
        //$font->file($fontPath);
        $font->file('./app/fonts/st.ttf');
        $font->size(35);**/
        $img->text($creatorName, 550, 260, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($courseName, 960, 260, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($gradeName, 700, 365, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($workPlace, 500, 468, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($zmStyleName, 500, 570, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($zmgkkCategoryName, 730, 570, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($themeName, $categoryDistance, 675, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($date, $categoryDistance, 780, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($place, $categoryDistance, 885, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($target, $categoryDistance, 990, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });

        $img->text($remark, 500, 1075, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($zmrsInfo, 500, 1195, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($zmrzw, 960, 1195, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($fzrsInfo, 740, 1305, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($signDate, 830, 1650, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });

        $fileKey = md5($themeName.$creatorName.$date);
        $fileName = $fileKey.'.png';

        $img->save($savePath . '/' . $fileName);
        // dd(1);
        $fileSave = $this->generateFileSave($fileKey, $fileName);

        return $fileSave;
    }
    // 生成证明单
    public function generateWinZmd($request, $dicArr, $savePath)
    {
        $user = Auth::user();
        $imagePath = public_path('app/images/zmdjz.jpg');
        $fontPath = public_path('app/fonts/st.ttf');
        $fontPath = './app/fonts/st.ttf';
        $img = Image::make($imagePath)->resize(1200, 1700);
        $categoryDistance = in_array($request['activity_category'], ['EW_CLASS_MEETING_TABLE', 'TEARRESEARCH_OPEN_TABLE']) ? 470 : 710;

        $creatorName = $this->to_unicode($user->nickname);
        $themeName = $this->to_unicode($request['name']);
        $workPlace = $this->to_unicode('上海市徐汇区汇师小学');
        $zmrzw = $this->to_unicode($request['witness_position']);

        $courseDic = $dicArr->where('optionId', $request['course'])->first();
        $courseName = $courseDic ? $this->to_unicode($courseDic->selectValue) : '';
        $gradeDic = $dicArr->where('optionId', $request['grade'])->first();
        $gradeName = $courseDic ? $this->to_unicode($gradeDic->selectValue) : '';
        $levelDic = $dicArr->where('optionId', $request['level'])->first();
        $levelName = $courseDic ? $levelDic->selectValue : '';
        $date = $this->to_unicode($request['begin_date']);
        $signDate = date('Y年m月d日', strtotime($request['begin_date']));
        $place = $this->to_unicode($request['place']);
        $target = $this->to_unicode($request['target']);
        $remark = $request['zmd_remark'] ? $this->to_unicode($request['zmd_remark']) : '';

        // $zmStyle = $request['zm_style'] == 1 ? '公开课' : '研究课';
        // $zmStyleName = $this->to_unicode($zmStyle);
        // $zmgkkCategory = '';
        // switch ($request['zm_gkk_category']) {
        //     case 1:
        //         $zmgkkCategory = $levelName . '讲座';
        //         break;
        //     case 2:
        //         $zmgkkCategory = $levelName . '交流';
        //         break;
        // }
        // $zmgkkCategoryName = $zmgkkCategory ? $this->to_unicode($zmgkkCategory) : '';
        $zmStyleName = $this->to_unicode('校级公开课');
        $zmgkkCategoryName = $this->to_unicode('校级讲座');


        $zmrs = User::whereIn('id', $request['zmr_ids'])->get();
        $fzrs = User::whereIn('id', $request['fzr_ids'])->get();
        $zmrsInfo = $zmrs->count() > 0 ? $this->to_unicode($zmrs->pluck('nickname')->implode(' ')) : '';
        $fzrsInfo = $zmrs->count() > 0 ? $this->to_unicode($fzrs->pluck('nickname')->implode(' ')) : '';

        $img->text($creatorName, 470, 280, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($courseName, 920, 280, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($gradeName, 700, 360, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($workPlace, 600, 440, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($zmStyleName, 470, 520, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($zmgkkCategoryName, 710, 520, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });

        $img->text($themeName, $categoryDistance, 605, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($date, $categoryDistance, 690, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($place, $categoryDistance, 770, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($target, $categoryDistance, 850, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });

        $img->text($remark, 710, 930, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($zmrsInfo, 470, 1040, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($zmrzw, 920, 1040, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($fzrsInfo, 700, 1140, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });
        $img->text($signDate, 780, 1480, function($font) {
            $fontPath = public_path('app/fonts/st.ttf');
            $font->file($fontPath);
            $font->size(35);
        });

        $fileKey = md5($themeName.$creatorName.$date);
        $fileName = $fileKey.'.png';

        $img->save($savePath . '/' . $fileName);
        dd(1);
        $fileSave = $this->generateFileSave($fileKey, $fileName);

        return $fileSave;
    }

    public function generateFileSave($fileKey, $fileName)
    {
        $now = now();
        $fileShowName = '证明单.png';

        $fileObj = File::create([
            'file_name' => '证明单.png',
            'file_key'  => $fileKey,
            'extension' => 'png',
            'file_path' => 'image/'.$now->format('Ym').'/'.$fileName,
            'file_dir'  => '/back-end/uploadfiles/'
        ]);

        $result[] = [
            'id'        => $fileObj->id,
            'editable'  => true,
            'file_name'  => $fileShowName,
            'file_path'  => $fileObj->id.'/'.$fileKey,
            'extension' => 'png',
            'field'     => 'zmd'
        ];

        return $result;
    }

    // 将 utf-8 字符串转为 Unicode 编码格式
    function to_unicode($string,$flag=true)
    {
        if($flag) {
            $str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');
            $arrstr = str_split($str, 2);
            $unistr = '';
            foreach ($arrstr as $n) {
                $dec = hexdec(bin2hex($n));
                $unistr .= '&#' . $dec . ';';
            }
            return $unistr;
        }else{
            return $string;
        }
    }

    /**
     * 推送
     * @author qiankun
     * @datetime 2025-03-18
     */
    public function push($request)
    {
        $id = $request['id'];
        $participantInfo = Participant::query()->where(['activity_info_id' => $id,'user_id' => $request['user_id']])->firstOrFail();
        $participantInfo->is_push  = $participantInfo->is_push ? 0 : 1;
        $participantInfo->save();
        //$activity = ActivityInfo::query()->where(['id' => $id])->firstOrFail();
        //$activity->save();
        Files::where(['ilk_id'=>$id,'ilk_type' => 1])->update(['is_push' => $participantInfo->is_push]);
        return $participantInfo->is_push;
    }
}
